package com.hw.saweb.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.sign.SaSignUtil;
import cn.dev33.satoken.util.SaResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: sa-token-start
 * @author: hewei
 * @date: 2023-09-13 16:24
 *
 * 接口签名功能验证
 **/

@Slf4j
@RestController
@RequestMapping("/sign")
public class ApiSignController {

    /*生成签名接口*/
    @RequestMapping("/generate")
    public SaResult generate(String username,String password){
        Map<String, Object> paramMap = new LinkedHashMap<>();
        paramMap.put("username", username);
        paramMap.put("password", password);

        // 接口参数签名，并补全 timestamp、nonce、sign 参数，并序列化为 kv 字符串
        String paramStr = SaSignUtil.addSignParamsAndJoin(paramMap);

        String url="http://localhost:9000/sign/check";
        // 将参数字符串拼接在请求地址后面
        url += "?" + paramStr;

        log.info(">>> sa-token 接口签名完成,签名后地址：{}",url);
        return SaResult.ok(url);
    }

    /*验证签名接口*/
    @RequestMapping("/check")
    public SaResult check(String username,String password){
        // 1、校验请求中的签名
        log.info(">>> sa-token 接口签名校验是否通过：{}",SaSignUtil.isValidRequest(SaHolder.getRequest()));

        SaSignUtil.checkRequest(SaHolder.getRequest());

        return SaResult.ok("sa-token 接口签名校验通过!");
    }
}
